<template>
  <div class="category-container">
    <div class="bg-gray-linear">
      <div class="max-w-11xl mx-auto px-4 pt-6 pb-4">
        <div class="breadcrumbs space-x-2 text-base flex flex-wrap items-center mb-4">
          <common-link path="/"
            class="text-gray-1000 hover:text-purple-1200 go-home">
            {{$t('home')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <common-link path="/category"
            class="text-gray-1000 hover:text-purple-1200 go-prev">
            {{$t('categories')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <span class="text-gray-1400 text-base">
            {{categoryName ? categoryName : $route.params.handle}}
          </span>
        </div>

        <div class="lg:flex lg:items-center lg:gap-x-5">
          <div class="lg:flex-1">
            <sponsored-by class="mb-5 text-lg text-gray-1000 font-semibold text-center"></sponsored-by>

            <h1 class="text-5xl leading-normal text-gray-1000 font-bold break-words text-center">{{$t('category_theBestAIToolsInYear',{categoryName: categoryName,year: fullYear, num: total_count})}}</h1>
            <p class="text-sm leading-normal text-gray-1000 mt-2 text-center mx-auto max-w-4xl"
              v-if="toolsArr && toolsArr.length > 0"
              v-html="$t('category_bannerDesc',{num: toolsArr.length, toolsList: toolsArr.join(', '), categoryName: categoryName,year: fullYear})">
            </p>
          </div>
        </div>
      </div>

      <div class="max-w-11xl mx-auto px-4 py-4">
        <div class="xl:grid xl:grid-cols-5 xl:gap-5 items-start">
          <div class="xl:col-span-4"
            :class="{'xl:col-span-5': !(recommendToolsList && recommendToolsList.length > 0)}">
            <div class="flex items-center flex-wrap gap-4">
              <div class="flex-1 flex items-center flex-wrap gap-4">
                <common-square-sort :targetObj="sortOptions"
                  :hasBorder="true"
                  :sort="sort"
                  class="block md:inline-block w-full sm:w-auto"
                  @toSearch="toSearch"></common-square-sort>
                <common-square-sort :targetObj="attributeFeaturesOptions"
                  :hasBorder="true"
                  :sort="attribute_features"
                  class="block md:inline-block w-full sm:w-auto"
                  @toSearch="toSearchFilter"></common-square-sort>
              </div>
              <div class="w-full sm:w-auto flex-shrink-0">
                <min-share></min-share>
              </div>
            </div>
            <div class="tools grid gap-5 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 mt-7"
              :class="{'xl:grid-cols-5': !(recommendToolsList && recommendToolsList.length > 0)}"
              v-if="toolsList && toolsList.length > 0">
              <min-tool v-for="(item, key) in toolsList"
                :key="item.handle+'-'+key"
                :toolPosIndex="key"
                :toolPosition="`${category_detail.handle}-list`"
                :toolsData="item"
                :specialHandle="$route.params.handle"
                :lazyLoad="key < 4 ? false : true"></min-tool>
            </div>

            <div class="w-2/4 mx-auto mt-10 text-center"
              v-if="toolsList && toolsList.length>0">
              <template v-if="toolsList && toolsList.length>0 && next_page_url">
                <el-button type="text"
                  key="loading"
                  class="cursor-default loading-btn"
                  v-if="loading">
                  <img :src="loadingSrc"
                    class="loading"
                    alt=""
                    srcset="">
                </el-button>
                <el-button v-else
                  key="loadMore"
                  @click="loadMore">
                  {{ $t('category_loadMore') }}
                </el-button>
              </template>

              <div v-else
                class="flex items-center gap-5 mt-12 py-3">
                <div class="flex-1 h-px bg-gray-1600"></div>
                <span class="text-sm text-purple-1300">{{ $t('category_end') }}</span>
                <div class="flex-1 h-px bg-gray-1600"></div>
              </div>
            </div>
            <el-empty v-if="(!toolsList || toolsList.length===0) && !loading"
              :description="$t('category_noData')"></el-empty>

            <div class="xl:grid xl:grid-cols-4 xl:gap-5 items-start max-w-6xl mx-auto">
              <div class="hidden xl:block xl:col-span-1 h-1"
                v-if="recommendToolsList && recommendToolsList.length > 0">

              </div>
              <div class="xl:col-span-3"
                :class="{'xl:col-span-4': !(recommendToolsList && recommendToolsList.length > 0)}">
                <div class="py-20 px-6 md:px-8 mt-14 rounded-md bg-purple-2100"
                  v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.introduction)">
                  <div class="flex items-center justify-center lg:justify-between gap-5 flex-wrap">
                    <h2 class="text-4xl text-gray-1000 flex-1 text-center font-bold"
                      v-html="$t('category_whatIsTool', {categoryName:categoryName})"></h2>
                    <p class="text-lg text-gray-1000 w-full sm:max-w-xs xl:max-w-md break-words mx-auto lg:mx-0">
                      {{category_detail.ai_content.introduction}}
                    </p>
                  </div>
                </div>
                <div class="pb-16 lg:pb-24">
                  <div class="mt-20 lg:mt-24"
                    v-if="top_list && top_list.length > 0">
                    <div class="bg-purple-2100 px-7 pt-10 pb-7 rounded">
                      <h2 class="text-4xl text-gray-1000 text-center font-bold mb-10">
                        {{$t('category_topTools',{categoryName:categoryName,num: top_list.length})}}
                      </h2>
                      <div class="tTable"
                        style="overflow-x: auto;">
                        <table style="width: 100%; min-width: 725px;">
                          <thead>
                            <tr>
                              <th style="width: 25%">

                              </th>
                              <th style="width: 25%">
                                <div class="cell text-base">
                                  {{$t('category_th_coreFeatures')}}
                                </div>
                              </th>
                              <th style="width: 25%">
                                <div class="cell text-base">
                                  {{$t('category_th_price')}}
                                </div>
                              </th>
                              <th style="width: 25%">
                                <div class="cell text-base">
                                  {{$t('category_th_howToUse')}}
                                </div>
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr class="el-table__row"
                              v-for="(row, key) in top_list"
                              :key="key">
                              <td>
                                <h3 class="cell">
                                  <common-link path="/tool/:handle"
                                    @click.native="handleExp(key, row, `${category_detail.handle}-top10Tools`)"
                                    :params="{ handle:row.handle }"
                                    :data-handle="row.handle"
                                    :data-advertisement_id="row.advertisement_id ? row.advertisement_id : ''"
                                    :data-position="`${category_detail.handle}-top10Tools`"
                                    :data-index="key"
                                    class="text-lg text-purple-1300 font-bold hover:opacity-95 go-tool leading-5.5 tool-dom"
                                    target="_blank">
                                    {{$websiteName(row)}}
                                  </common-link>
                                </h3>
                              </td>
                              <td>
                                <div class="cell">
                                  <p class="text-base text-gray-1000 break-words tool-desc leading-5.5"
                                    v-if="hasRealVal(row.ai_content) && hasRealVal(row.ai_content.core_features) && row.ai_content.core_features.length > 0"
                                    :title="row.ai_content.core_features"
                                    v-html="row.ai_content.core_features.join('<br/>')">
                                  </p>
                                </div>
                              </td>
                              <td>
                                <div class="cell">
                                  <p class="text-base text-gray-1000 break-words tool-desc leading-5.5"
                                    v-if="hasRealVal(row.ai_content) && hasRealVal(row.ai_content.pricing) && row.ai_content.pricing.length > 0">
                                    <template v-for="(titem, tKey) in row.ai_content.pricing">
                                      {{`${titem.name} ${titem.price} ${titem.description}`}}
                                      <br v-if="tKey !== row.ai_content.pricing.length - 1" />
                                    </template>
                                  </p>
                                </div>
                              </td>
                              <td>
                                <div class="cell">
                                  <p class="text-base text-gray-1000 break-words tool-desc leading-5.5"
                                    v-if="hasRealVal(row.ai_content) && hasRealVal(row.ai_content.how_to_use)"
                                    :title="row.ai_content.how_to_use">
                                    {{row.ai_content.how_to_use}}
                                  </p>
                                </div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                  <div class="mt-20 lg:mt-28">
                    <div class="px-5">
                      <h2 class="text-4xl text-gray-1000 text-center font-bold mb-10">
                        {{$t('category_newestAIWebsites',{categoryName:categoryName})}}
                      </h2>
                      <div class="newest-tools px-4 md:px-7">
                        <newest-tools :toolsData="sidebarToosList"
                          :toolPosition="`${category_detail.handle} Newest`"
                          v-if="sidebarToosList && sidebarToosList.length>0"></newest-tools>
                      </div>
                    </div>
                  </div>
                  <div class="mt-20 lg:mt-28"
                    v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.core_features) && category_detail.ai_content.core_features.length > 0">
                    <div class="px-5">
                      <h2 class="text-4xl text-gray-1000 text-center font-bold mb-16">
                        {{$t('category_coreFeatures',{categoryName:categoryName})}}
                      </h2>
                      <div class="space-y-5">
                        <div class="flex items-start gap-4"
                          v-for="(item, key) in category_detail.ai_content.coreFeaturesList">
                          <svg-icon iconName="check_4"
                            class="text-3xl flex-shrink-0" />
                          <div class="flex-1">
                            <h3 class="text-26 leading-7 text-gray-1000 font-bold">{{item[0]}}</h3>
                            <div class="text-base text-gray-1000 mt-2"
                              v-if="item.length > 1">{{item[1]}}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="mt-20 lg:mt-40 space-y-5"
                    v-if="hasRealVal(category_detail.ai_content)">
                    <div class="border border-gray-1600 rounded-md py-7 px-5 sm:px-7"
                      v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.use_cases) && Array.isArray(category_detail.ai_content.use_cases) && category_detail.ai_content.use_cases.length > 0">
                      <h2 class="text-3xl text-gray-1000 text-center font-bold mb-6">{{$t('category_whaIsCanDo',{categoryName:categoryName})}}</h2>
                      <p class="text-lg text-gray-1000 whitespace-pre-line"
                        v-for="(item, key) in category_detail.ai_content.use_cases"
                        :key="key"
                        v-html="item">
                      </p>
                    </div>
                    <div class="border border-gray-1600 rounded-md py-7 px-5 sm:px-7"
                      v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.reviews)">
                      <h2 class="text-3xl text-gray-1000 text-center font-bold mb-6">{{$t('category_nameReview',{categoryName:categoryName})}}</h2>
                      <p class="text-lg text-gray-1000 whitespace-pre-line"
                        v-html="category_detail.ai_content.reviews"></p>
                    </div>
                    <div class="border border-gray-1600 rounded-md py-7 px-5 sm:px-7"
                      v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.user_case) && Array.isArray(category_detail.ai_content.user_case) && category_detail.ai_content.user_case.length > 0">
                      <h2 class="text-3xl text-gray-1000 text-center font-bold mb-6">{{$t('category_whoIsSuitableToUse',{categoryName:categoryName})}}</h2>
                      <p class="text-lg text-gray-1000 whitespace-pre-line"
                        v-for="(item, key) in category_detail.ai_content.user_case"
                        :key="key"
                        v-html="item">
                      </p>
                    </div>
                    <div class="border border-gray-1600 rounded-md py-7 px-5 sm:px-7"
                      v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.usage)">
                      <h2 class="text-3xl text-gray-1000 text-center font-bold mb-6">{{$t('category_howDoesWork',{categoryName:categoryName})}}</h2>
                      <p class="text-lg text-gray-1000 whitespace-pre-line"
                        v-html="category_detail.ai_content.usage">
                      </p>
                    </div>
                    <div class="border border-gray-1600 rounded-md py-7 px-5 sm:px-7"
                      v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.benefits) && Array.isArray(category_detail.ai_content.benefits) && category_detail.ai_content.benefits.length > 0">
                      <h2 class="text-3xl text-gray-1000 text-center font-bold mb-6">{{$t('category_advantagesOf',{categoryName:categoryName})}}</h2>

                      <p class="text-lg text-gray-1000 whitespace-pre-line"
                        v-for="(item, key) in category_detail.ai_content.benefits"
                        :key="key"
                        v-html="item">
                      </p>
                    </div>
                  </div>

                  <div class="mt-20 lg:mt-28 rounded-md bg-purple-2100 social-swiper"
                    v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.social_proof) && Array.isArray(category_detail.ai_content.social_proof) && category_detail.ai_content.social_proof.length > 0">
                    <no-ssr>
                      <div v-swiper:mySwiper="swiperOption">
                        <div class="swiper-wrapper">
                          <div class="swiper-slide rounded-md py-20 px-10 md:px-24"
                            style="width: 100%;"
                            v-for="(item, key) in category_detail.ai_content.social_proof"
                            :key="key">
                            <div class="text-center">
                              <el-rate v-model="rate"
                                disabled
                                score-template="{value}">
                              </el-rate>
                            </div>
                            <p class="text-center text-xl text-black break-words mt-6">
                              {{item}}
                            </p>
                            <div class="text-center text-xl text-black mt-8 font-semibold">Sam Duncan</div>
                          </div>
                        </div>
                        <div class="swiper-pagination" />
                        <div slot="button-prev"
                          class="swiper-button-prev"
                          :class="{'opacity-0': !isLoaded}" />
                        <div slot="button-next"
                          class="swiper-button-next"
                          :class="{'opacity-0': !isLoaded}" />
                      </div>
                    </no-ssr>
                    <!-- 幻灯片 结束 -->
                  </div>

                  <div class="mt-20 lg:mt-40 space-y-5"
                    v-if="hasRealVal(category_detail.ai_content) && hasRealVal(category_detail.ai_content.faq) && category_detail.ai_content.faq.length> 0">
                    <h2 class="text-4xl text-gray-1000 text-center font-bold mb-10">
                      {{$t('category_faqAbout',{categoryName:categoryName})}}
                    </h2>
                    <div>
                      <dl class="space-y-6 divide-y divide-gray-1600 hover:divide-y">
                        <div v-for="(faq, key) in category_detail.ai_content.faq"
                          :key="`faq-${key}`"
                          class="pt-6">
                          <dt class="flex items-start justify-between text-left text-xl leading-6 text-gray-1000 hover:text-purple-1300 cursor-pointer"
                            :class="{'text-purple-1300': faq.show,'opacity-90': faq.show }"
                            :key="key"
                            @click="show(key)">
                            <span>{{faq.q}}</span>
                            <span class="flex justify-center h-8 ml-8 -mt-1">
                              <svg xmlns="http://www.w3.org/2000/svg"
                                class="h-8 w-8"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke-width="1.5"
                                stroke="currentColor"
                                aria-hidden="true"
                                v-if="!faq.show">
                                <path stroke-linecap="round"
                                  stroke-linejoin="round"
                                  d="M12 6v12m6-6H6"></path>
                              </svg>
                              <svg xmlns="http://www.w3.org/2000/svg"
                                class="h-8 w-8"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke-width="1.5"
                                stroke="currentColor"
                                aria-hidden="true"
                                v-if="faq.show">
                                <path stroke-linecap="round"
                                  stroke-linejoin="round"
                                  d="M18 12H6"></path>
                              </svg>
                            </span>
                          </dt>
                          <dd class="mt-2 text-base text-gray-1000"
                            v-if="faq.show">
                            {{faq.a}}
                          </dd>
                        </div>
                      </dl>
                    </div>
                  </div>
                  <div class="mt-20 lg:mt-40 space-y-5"
                    v-if="otherCategory && otherCategory.length> 0">
                    <h2 class="text-4xl text-gray-1000 text-center font-bold mb-10">
                      {{$t('category_moreCategories')}}
                    </h2>
                    <div class="grid gap-5 sm:grid-cols-3">
                      <common-link v-for="(item, key) in otherCategory"
                        path="/category-attribute/:handle"
                        target="_blank"
                        :params="{ handle:item.handle }"
                        :key="`category-${item.handle}-${key}`"
                        class="text-base text-gray-1000 border-gray-2000 border rounded-md px-5 py-4 truncate  hover:border-purple-1300 hover:text-purple-1300 hover:bg-purple-2200">
                        {{item.show_name}}
                      </common-link>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="hidden xl:block xl:col-span-1"
            v-if="recommendToolsList && recommendToolsList.length > 0">
            <h3 class="text-34 text-gray-34 font-bold">{{$t('category_featured')}}</h3>
            <div class="tools space-y-4 mt-7 px-3.5 py-4 bg-white rounded-lg">
              <template v-for="(item, key) in recommendToolsList">
                <min-tool-featured :key="item.handle+'-'+key"
                  v-if="key< 20"
                  :toolPosIndex="key"
                  :toolsData="item"></min-tool-featured>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import moment from 'moment'
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapActions, mapState, mapMutations } from 'vuex'
export default {
  name: 'CategoryDetail',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
      script: [
        {
          json: {
            '@context': 'https://schema.org',
            '@type': 'Article',
            headline: this.$t('category_theBestAIToolsIn', {
              categoryName: this.categoryName,
              year: this.fullYear,
              num: this.total_count,
            }),
            image: [],
            dateModified: this.category_detail.updated_at
              ? moment(this.category_detail.updated_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            datePublished: this.category_detail.created_at
              ? moment(this.category_detail.created_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            author: {
              '@type': 'Organization',
              name: 'toolify',
              url: 'https://www.toolify.ai',
            },
            description: this.description,
            articleSection: 'Technology',
            mainEntityOfPage: `https://www.toolify.ai${this.$route.fullPath}`,
            publisher: {
              '@context': 'https://www.toolify.ai',
              '@type': 'Organization',
              name: 'Toolify',
              legalName: 'Toolify Inc',
              url: 'https://www.toolify.ai',
              logo: 'https://www.toolify.ai/favicon.ico',
              foundingDate: '2023',
              founders: [
                {
                  '@type': 'Organization',
                  name: 'toolify',
                },
              ],
              address: {
                '@type': 'PostalAddress',
                streetAddress: '1942 Broadway St STE 314C Boulder',
                addressLocality: 'Colorado',
                addressRegion: 'CO',
                postalCode: '80302',
                addressCountry: 'US',
              },
              contactPoint: {
                '@type': 'ContactPoint',
                contactType: 'customer support',
                email: 'business@toolify.ai',
              },
              sameAs: ['https://twitter.com/samChan3890089'],
            },
            name: this.title,
            breadcrumb: {
              '@type': 'BreadCrumbList',
              itemListElement: [
                {
                  '@type': 'ListItem',
                  position: 1,
                  name: this.$t('home'),
                  item: `https://www.toolify.ai${
                    this.locale === 'en' ? '' : `/${this.locale}`
                  }`,
                },
                {
                  '@type': 'ListItem',
                  position: 2,
                  name: this.$t('categories'),
                  item: `https://www.toolify.ai${
                    this.locale === 'en' ? '' : `/${this.locale}`
                  }/category`,
                },
                {
                  '@type': 'ListItem',
                  position: 3,
                  name: this.categoryName
                    ? this.categoryName
                    : this.$route.params.handle,
                },
              ],
            },
            mainEntity: this.faqArr,
          },
          type: 'application/ld+json',
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    let pageDesc = app.$cookies.get('pageDesc')
    let date = new Date()
    let fullYear = date.getFullYear()
    try {
      let res = {}
      let description, title
      let recommendToolsList = []

      let faqArr = []

      let [toolsRes, langRes] = await Promise.all([
        await $axiosApi.categoryAttributeDetail({
          handle: encodeURIComponent(params.handle),
          order_by: 'category_attribute_correlation',
          page: 1,
          per_page: 100,
        }),
        await $axiosApi.getLanguagesMul(),
        /* $axiosApi.getTools({
          page: 1,
          per_page: 100,
          history_has_recommended: 1,
        }), */
      ])

      if (toolsRes.code === 200) {
        res.toolsList =
          toolsRes.data.data && toolsRes.data.data.length > 0
            ? toolsRes.data.data
            : []
        res.total = toolsRes.data.total
        res.total_count = toolsRes.data.total_count
        res.page = toolsRes.data.current_page ? toolsRes.data.current_page : 1
        res.per_page = toolsRes.data.per_page ? toolsRes.data.per_page : 18
        res.next_page_url = toolsRes.data.next_page_url
          ? toolsRes.data.next_page_url
          : null

        res.otherCategory = toolsRes.data.next_and_last_name
        res.sidebarToosList = toolsRes.data.new_list
        if (
          toolsRes.data.category_detail &&
          toolsRes.data.category_detail.ai_content &&
          toolsRes.data.category_detail.ai_content.faq
        ) {
          toolsRes.data.category_detail.ai_content.faq.forEach((item) => {
            item.show = false
          })
        }
        if (
          toolsRes.data.category_detail &&
          toolsRes.data.category_detail.ai_content &&
          toolsRes.data.category_detail.ai_content.core_features &&
          toolsRes.data.category_detail.ai_content.core_features.length > 0
        ) {
          let coreFeaturesList = []
          toolsRes.data.category_detail.ai_content.core_features.forEach(
            (item) => {
              let coreItem = []
              const parts = item.split(item.indexOf(':') >= 0 ? ':' : '：')
              coreItem[0] = parts[0]
              if (parts.length > 1) {
                coreItem[1] = parts.slice(1).join(':').trim()
              }
              coreFeaturesList.push(coreItem)
            }
          )
          toolsRes.data.category_detail.ai_content.coreFeaturesList =
            coreFeaturesList
        }
        res.category_detail = toolsRes.data.category_detail
        res.top_list = toolsRes.data.top_list
        
        res.region_avg_visited_count = toolsRes.data.region_avg_visited_count
        res.million_tool_count = toolsRes.data.million_tool_count

        res.categoryName = res.category_detail.show_name

        recommendToolsList =
          toolsRes.data.featured_list && toolsRes.data.featured_list.length > 0
            ? toolsRes.data.featured_list
            : []

        let toolsArr = []
        let toolsArrDesc = []

        function websiteName(tool) {
          let toolName = tool.name
          if (tool.website && tool.website && tool.website.name) {
            toolName = tool.website.name
          }
          return toolName
        }

        res.toolsList.forEach((item, key) => {
          if (key < 10) {
            toolsArr.push(websiteName(item))
          }
          if (key < 5) {
            toolsArrDesc.push(websiteName(item))
          }
        })
        res.toolsArr = toolsArr
        res.toolsArrDesc = toolsArrDesc

        title = app.i18n.t('category_detail_page_title', {
          categoryName: res.categoryName,
          num: res.total_count,
        })

        description = app.i18n.t('category_detail_page_desc', {
          categoryName: res.categoryName,
          list: toolsArrDesc.join(','),
          num: res.total_count,
        })

        if (res.category_detail && res.category_detail.ai_content) {
          if (
            res.category_detail.ai_content.faq &&
            res.category_detail.ai_content.faq.length > 0
          ) {
            res.category_detail.ai_content.faq.forEach((item) => {
              faqArr.push({
                '@type': 'Question',
                name: item.q,
                acceptedAnswer: {
                  '@type': 'Answer',
                  text: item.a,
                },
              })
            })
          }
          if (res.category_detail.ai_content.introduction) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_whatIsTool', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.introduction,
              },
            })
          }
          if (
            res.category_detail.ai_content.use_cases &&
            Array.isArray(res.category_detail.ai_content.use_cases) &&
            res.category_detail.ai_content.use_cases.length > 0
          ) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_whaIsCanDo', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.use_cases.join('. '),
              },
            })
          }
          if (res.category_detail.ai_content.reviews) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_nameReview', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.reviews,
              },
            })
          }
          if (
            res.category_detail.ai_content.user_case &&
            Array.isArray(res.category_detail.ai_content.user_case) &&
            res.category_detail.ai_content.user_case.length > 0
          ) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_whoIsSuitableToUse', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.user_case.join('. '),
              },
            })
          }
          if (res.category_detail.ai_content.usage) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_howDoesWork', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.usage,
              },
            })
          }
          if (
            res.category_detail.ai_content.benefits &&
            Array.isArray(res.category_detail.ai_content.benefits) &&
            res.category_detail.ai_content.benefits.length > 0
          ) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n
                .t('category_advantagesOf', {
                  categoryName: res.categoryName,
                })
                .replace(/<[^>]+>/g, ''),
              acceptedAnswer: {
                '@type': 'Answer',
                text: res.category_detail.ai_content.benefits.join('. '),
              },
            })
          }
        }
        if (res.top_list && res.top_list.length > 0) {
          let topToolsArr = []
          res.top_list.forEach((item, key) => {
            topToolsArr.push(websiteName(item))
          })
          faqArr.push({
            '@type': 'Question',
            name: app.i18n.t('category_topTools', {
              categoryName: res.categoryName,
              num: res.top_list.length,
            }),
            acceptedAnswer: {
              '@type': 'Answer',
              text: topToolsArr.join(', '),
            },
          })
        }
      } else {
        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: toolsRes.code,
          })
        }
      }

      if (!description) {
        let curLocale = store.state.locale
        if (
          langRes.code === 200 &&
          langRes.data &&
          langRes.data.languages &&
          langRes.data.languages.description &&
          langRes.data.languages.description.length > 0 &&
          langRes.data.languages.description[0].content &&
          (langRes.data.languages.description[0].content[curLocale] ||
            langRes.data.languages.description[0].content.default)
        ) {
          if (langRes.data.languages.description[0].content[curLocale]) {
            description =
              langRes.data.languages.description[0].content[curLocale]
          } else {
            description = langRes.data.languages.description[0].content.default
          }

          app.$cookies.set('pageDesc', description, {
            maxAge: 60 * 60 * 24 * 7,
            path: '/',
          })
        } else if (pageDesc) {
          description = pageDesc
        }
      }

      /* if (recommendRes.code === 200) {
        recommendToolsList =
          recommendRes.data.data && recommendRes.data.data.length > 0
            ? recommendRes.data.data
            : []
      } */

      return {
        ...res,
        title,
        description,
        fullYear,
        recommendToolsList,
        faqArr,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      countries: (state) => state.countries,
    }),
  },
  /* watch: {
    $route: {
      handler(route) {
        if (route.name === this.$route.name
        ) {
          this.getList(1)
        }
      },
      deep: true,
      immediate: true,
    },
  }, */
  mixins: [mixinsExposure],
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      toolsList: [],
      page: 1,
      per_page: 100,
      next_page_url: null,
      keyword: null,
      errorImage: require('@/static/images/default.webp'),
      loading: false,
      total: 0,
      total_count: 0,

      categoryName: null,
      otherCategory: [],
      sidebarToosList: [],
      category_detail: {},
      toolsArr: [],
      toolsArrDesc: [],

      top_list: [],
      
      region_avg_visited_count: 0,
      million_tool_count: 0,

      title: null,
      description: null,
      fullYear: null,

      fLoading: false,
      sort: 'category_attribute_correlation',
      sortOptions: {
        isShowOptions: false,
        options: [
          {
            label: 'category_sortMonthVisitedCount',
            val: 'month_visited_count',
          },
          { label: 'category_sortCollectedCount', val: 'collected_count' },
          { label: 'category_sortCreatedAt', val: 'created_at' },
          { label: 'category_correlation', val: 'category_attribute_correlation' },
        ],
      },

      attribute_features: null,
      attributeFeaturesOptions: {
        isShowOptions: false,
        options: [
          {
            label: 'category_default',
            val: null,
          },
          {
            label: 'category_website',
            val: 'website',
          },
          {
            label: 'category_browser_extension',
            val: 'browser-extension',
          },
          {
            label: 'category_app',
            val: 'app',
          },
        ],
      },

      recommendToolsList: [],

      faqArr: [],
      loadingSrc: require('@/static/images/loading.png'),

      isLoaded: false,
      rate: 5,
      rateColor: ['#7150E6', '#977FEA', '#F7BA2A'],
      swiperOption: {
        loop: true,
        // 配置分页
        pagination: {
          el: '.swiper-pagination', // 分页的dom节点
          type: 'progressbar',
        },
        // 配置导航
        navigation: {
          nextEl: '.swiper-button-next', // 下一页dom节点
          prevEl: '.swiper-button-prev', // 前一页dom节点
        },
      },
    }
  },
  created() {
    /* if (process.browser && this.serverLoaded) {
      this.loading = true
      this.getList(1)
    } */
  },
  mounted() {
    this.$nextTick(() => {
      this.isLoaded = true
    })
  },
  methods: {
    ...mapActions(['exposure']),
    ...mapMutations(['SET_RetrackExposure']),
    loadMore() {
      if (this.next_page_url && !this.loading) {
        this.getList(this.page + 1)
      }
    },
    async getList(page) {
      this.loading = true
      try {
        const res = await this.$axiosApi.categoryAttributeDetail({
          handle: encodeURIComponent(this.$route.params.handle),
          order_by: this.sort,
          page: page,
          per_page: 100,
          attribute_features: this.attribute_features,
        })

        this.loading = false

        if (res.code === 200) {
          if (page === 1) {
            this.toolsList = res.data.data
          } else {
            this.toolsList = this.toolsList.concat(res.data.data)
          }

          this.total = res.data.total
          this.page = res.data.current_page ? res.data.current_page : 1
          this.per_page = res.data.per_page ? res.data.per_page : 18
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null

          this.SET_RetrackExposure(Date.now())
        }
      } catch (error) {
        this.loading = false
      }
    },

    async toSearch(val) {
      this.fLoading = true
      this.sort = val
      this.sortOptions.isShowOptions = false

      if (
        this.sort === 'month_visited_count' &&
        (this.attribute_features === 'browser-extension' ||
          this.attribute_features === 'app')
      ) {
        this.attribute_features = null
      }

      await this.getList(1)
      this.fLoading = false
    },

    async toSearchFilter(val) {
      this.fLoading = true
      this.attribute_features = val
      this.attributeFeaturesOptions.isShowOptions = false

      if (
        (this.attribute_features === 'browser-extension' ||
          this.attribute_features === 'app') &&
        this.sort === 'month_visited_count'
      ) {
        this.sort = 'created_at'
      }
      await this.getList(1)
      this.fLoading = false
    },

    handleExp(key = 0, toolsData, toolPosition) {
      this.getThrottledClickFunction(toolsData, key, toolPosition)()
    },
    getThrottledClickFunction(toolsData, key, toolPosition) {
      let functionKey = `${toolsData.handle}-${key}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exporeData = this.getExporeData(
            toolsData,
            toolPosition,
            key,
            false
          )
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },

    show(key) {
      this.category_detail.ai_content.faq[key].show =
        !this.category_detail.ai_content.faq[key].show
    },
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
  },
}
</script>

<style lang='scss' scoped>
.category-container {
  background: #f8f9fb;
  ::v-deep .common-square-sort {
    .dropdown {
      height: 42px;
      min-width: 220px;
    }
  }
  ::v-deep .el-divider__text {
    background-color: #f8f9fb;
  }

  .bg-gray-linear {
    background: linear-gradient(180deg, #f8f9fb 0%, #ffffff 100%);
  }
  .insights-item {
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.08);
    border-radius: 8px;
    border: 1px solid #e5e5e5;
  }
  .tTable {
    background: #ffffff;
    border: 1px solid #e5e5e5;
    border-radius: 6px;
    table {
      table-layout: fixed;
      td,
      th {
        box-sizing: border-box;
        min-width: 0;
        position: relative;
        text-align: left;
        text-overflow: ellipsis;
        vertical-align: middle;
        .cell {
          box-sizing: border-box;
          display: inline-block;
          padding-left: 24px;
          padding-right: 24px;
          position: relative;
          vertical-align: middle;
          width: 100%;
          text-overflow: ellipsis;
          line-height: 23px;
          overflow: hidden;
        }
        &:first-child {
          .cell {
            padding-left: 24px;
          }
        }
        &:last-child {
          .cell {
            padding-right: 24px;
          }
        }
      }
      thead {
        tr {
          th {
            background: #f8f9fb;
            color: #191919;
            font-weight: 600;
            border-bottom: 1px solid #e5e5e5;
            font-size: 16px;
            padding: 15px 0;
            text-align: center;
          }
        }
      }
      tbody {
        tr {
          td {
            border-bottom: 1px solid #e5e5e5;
            color: #191919;
            font-size: 16px;
            padding-bottom: 16px;
            padding-top: 16px;
            transition: background-color 0.25s ease;
            & + td {
              border-left: 1px solid #e5e5e5;
            }
          }
          &:hover {
            td {
              background-color: #f5f7fa;
            }
          }

          &:last-child {
            td {
              border-bottom: 0;
            }
          }
        }
      }
    }
  }

  .newest-tools {
    background: #ffffff;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.12);
    border-radius: 6px;
  }
}

.social-swiper {
  overflow: hidden;
  ::v-deep .el-rate__icon {
    font-size: 28px;
    color: #7150e6 !important;
    margin-right: 2px;
  }
  .swiper-pagination {
    bottom: 30px;
    top: auto;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
    max-width: 146px;
    background: #e5e5e5;
    border-radius: 2px;
    overflow: hidden;
    height: 4px;
    ::v-deep .swiper-pagination-progressbar-fill {
      background: #7150e6;
      height: 4px;
    }
  }
  .swiper-button-prev,
  .swiper-container-rtl .swiper-button-next {
    background-image: url('@/static/images/left_outlined.png');
    background-size: 80% 80%;
    left: 30px;
    &:hover {
      opacity: 0.6;
    }
  }
  .swiper-button-next,
  .swiper-container-rtl .swiper-button-prev {
    background-image: url('@/static/images/right_outlined.png');
    background-size: 80% 80%;
    right: 30px;
    &:hover {
      opacity: 0.6;
    }
  }
}
</style>
